<?php
/**
 * 系统安装页面
 * 相对路径: install.php
 * 作者: 15058593138@qq.com
 */

require_once './inc/conn.php';
require_once './inc/pubs.php';
require_once './inc/sqls.php';

// 处理Ajax请求
if (isset($_GET['act']) && $_GET['act'] === 'install') {
    $demo = isset($_POST['demo']) ? intval($_POST['demo']) : 0;
    
    try {
        $db = new DB();
        
        // 创建用户表
        $userTable = TB_PREFIX . 'user';
        $sql = "CREATE TABLE IF NOT EXISTS `{$userTable}` (
            `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
            `手机号` varchar(32) NOT NULL COMMENT '手机号' DEFAULT '-',
            `密码` varchar(36) NOT NULL COMMENT '密码' DEFAULT '-',
            `VXID` varchar(36) NOT NULL COMMENT 'VXID' DEFAULT '-',
            `添加时间` datetime COMMENT '添加时间' DEFAULT CURRENT_TIMESTAMP,
            `改密时间` datetime COMMENT '改密时间',
            `最后登录` datetime COMMENT '最后登录',
            UNIQUE KEY `手机号` (`手机号`),
            KEY `VXID` (`VXID`),
            PRIMARY KEY (`id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8";
        
        if (!$db->query($sql)) {
            jsonMsg(0, '用户表创建失败');
        }
        
        // 插入管理员账户
        $adminPwd = pwdHash('admin123');
        $db->query("INSERT INTO `{$userTable}` (`手机号`, `密码`, `VXID`) VALUES ('admin', '{$adminPwd}', 'admin') ON DUPLICATE KEY UPDATE `密码`='{$adminPwd}'");
        
        // 插入普通用户账户
        $userPwd = pwdHash('user123');
        $db->query("INSERT INTO `{$userTable}` (`手机号`, `密码`) VALUES ('user', '{$userPwd}') ON DUPLICATE KEY UPDATE `密码`='{$userPwd}'");
        
        // 如果选择导入演示数据
        if ($demo === 1) {
            for ($i = 1; $i <= 36; $i++) {
                $phone = '1380000' . str_pad($i, 4, '0', STR_PAD_LEFT);
                $pwd = pwdHash('123456');
                $db->query("INSERT IGNORE INTO `{$userTable}` (`手机号`, `密码`) VALUES ('{$phone}', '{$pwd}')");
            }
            
            // 创建演示预定记录
            $today = date('Ymd');
            $tomorrow = date('Ymd', strtotime('+1 day'));
            $db->autoCreateDateTable($today);
            $db->autoCreateDateTable($tomorrow);
            
            $rooms = ['D301', 'S202', 'T101', 'B101'];
            $jiecis = ['S12', 'S34', 'X56', 'X78', 'WS9'];
            
            for ($i = 0; $i < 36; $i++) {
                $unid = makeUnid();
                $usid = '13800000' . str_pad(rand(1, 36), 4, '0', STR_PAD_LEFT);
                $room = $rooms[array_rand($rooms)];
                $jieci = $jiecis[array_rand($jiecis)];
                $seat = rand(1, 50);
                $hema = makeHema($tomorrow);
                
                $data = [
                    'unid' => $unid,
                    'usid' => $usid,
                    'room' => $room,
                    'ijie' => $tomorrow,
                    'days' => $jieci,
                    'iwei' => $seat,
                    'hema' => $hema,
                    'stats' => 1
                ];
                $db->insert(TB_PREFIX . 'recs_' . $tomorrow, $data);
            }
        }
        
        $db->close();
        jsonMsg(1, '安装成功！管理员账号：admin 密码：admin123；普通用户账号：user 密码：user123');
        
    } catch (Exception $e) {
        jsonMsg(0, '安装失败：' . $e->getMessage());
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>系统安装 - 教室座位预定系统</title>
    <link rel="stylesheet" href="./inc/pubs.css?v=<?php echo VERSION; ?>">
    <style>
        .install-box {
            max-width: 600px;
            margin: 50px auto;
            background: #fff;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .install-box h2 {
            text-align: center;
            color: #1a73e8;
            margin-bottom: 30px;
        }
        .check-item {
            padding: 10px;
            margin-bottom: 10px;
            border-left: 3px solid #28a745;
            background: #f8f9fa;
        }
        .check-item.fail {
            border-left-color: #dc3545;
        }
    </style>
</head>
<body>
    <div class="install-box">
        <h2>教室座位预定系统 - 安装向导</h2>
        
        <div id="checkResult">
            <h3>环境检查</h3>
            <div class="check-item">
                <strong>PHP版本：</strong><?php echo PHP_VERSION; ?> 
                <?php echo version_compare(PHP_VERSION, '7.0.0', '>=') ? '✓' : '✗ 需要PHP 7.0+'; ?>
            </div>
            <div class="check-item">
                <strong>MySQL扩展：</strong>
                <?php echo extension_loaded('mysqli') ? '✓ 已安装' : '✗ 未安装'; ?>
            </div>
            <div class="check-item">
                <strong>JSON扩展：</strong>
                <?php echo extension_loaded('json') ? '✓ 已安装' : '✗ 未安装'; ?>
            </div>
            <div class="check-item">
                <strong>数据库连接：</strong>
                <?php 
                try {
                    $testDb = new DB();
                    echo '✓ 连接成功';
                    $testDb->close();
                } catch (Exception $e) {
                    echo '✗ 连接失败：' . $e->getMessage() . '<br>请检查 inc/conn.php 中的数据库配置';
                }
                ?>
            </div>
            <div class="check-item">
                <strong>inc目录写入权限：</strong>
                <?php echo is_writable('./inc/') ? '✓ 可写' : '✗ 不可写'; ?>
            </div>
        </div>
        
        <form id="installForm" style="margin-top: 30px;">
            <div class="form-group">
                <label>
                    <input type="checkbox" name="demo" value="1"> 
                    导入演示数据（36个用户 + 预定记录）
                </label>
            </div>
            
            <div class="form-group">
                <button type="submit" class="btn btn-primary" style="width:100%">开始安装</button>
            </div>
            
            <div style="color:#666;font-size:12px;margin-top:15px;">
                <p>提示：</p>
                <ul style="margin-left:20px;">
                    <li>安装前请确保已创建数据库</li>
                    <li>默认管理员账号：admin / admin123</li>
                    <li>默认用户账号：user / user123</li>
                    <li>演示用户密码均为：123456</li>
                </ul>
            </div>
        </form>
    </div>
    
    <script src="./inc/pubs.js?v=<?php echo VERSION; ?>"></script>
    <script>
        document.getElementById('installForm').onsubmit = function(e) {
            e.preventDefault();
            
            const formData = getFormData('installForm');
            
            showLoading();
            ajax('install.php?act=install', formData, function(res) {
                hideLoading();
                if (res.code === 1) {
                    toast(res.msg, 'success');
                    setTimeout(() => {
                        window.location.href = 'index.php';
                    }, 2000);
                } else {
                    toast(res.msg, 'error');
                }
            });
        };
    </script>
</body>
</html>